//////////////////////////////////////////////////////////////////////////////////////////
// NAME: FileOperations.java								           					//
// AUTHOR: CDT Peter Lofreddo															//
// LAST MODIFIED: 12 February 2012														//
// DESCRIPTION: Contains File IO operations used for text files in Nullwall Application	//
// Firewall.																			//	
// LIMITATIONS: 																		//
// CITATIONS: Inside Individual Methods.												//
//																						//
////////////////////////////////////////////////////////////////////////////////////////// 
package com.Project.Nullwall;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import android.os.Environment;
import android.widget.Toast;

public class FileOperations extends Main
{
	
	public String[] ReadFileAsList(String fileName){
		//////////////////////////////////////////////////////////////////////////////////////////
		//NAME: ViewFileAsList(String fileName)										//
		//AUTHOR: CDT Peter Lofreddo 															//
		//LAST MODIFIED: 12 February 2012 														//
		//DESCRIPTION: Views file as a clickable ListView										//
		//LIMITATIONS: Search Queries cast to lowercase for ease of use.						//
		//CITATIONS: Adapted from http://stackoverflow.com/questions/8526831/					//
		//how-to-display-data-from-a-text-file-in-a-listview									//
		//																						//
		//////////////////////////////////////////////////////////////////////////////////////////
			
		try{
			File f = new File(Environment.getExternalStorageDirectory()
				+ "/Nullwall/" + fileName);
			FileInputStream fileIS = new FileInputStream(f);
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					fileIS));
			StringBuilder DbLines = new StringBuilder(); 
			String line = buf.readLine();
			while (buf.readLine() != null)
				{
				DbLines.append(line);
				DbLines.append("\r\n");
				}
			String[] ListItems = DbLines.toString().split("\r\n");

			return ListItems;
			}
	
	
 catch (FileNotFoundException e) {

	e.printStackTrace();

}
 catch (IOException e) {
		e.printStackTrace();

	}
 		return null;

}

	public void ReadFile(String fileName) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ReadLogFile() 																	//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 12 February 2012 														//
		// DESCRIPTION: Reads a file from mnt/sdcard/Nullwall_Logfiles, displays using textView	//
		// CITATIONS: Adapted from http://www.anddev.org/read_a_txt_file_ 						//
		// from_sd_card_in_a_real_device-t6619.html 											//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/Nullwall/" + fileName);
			FileInputStream fileIS = new FileInputStream(f);
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					fileIS));
			String readString = new String();
			tv.append(" \n\n Reading File: \n");

			// just reading each line and pass it on the debugger
			while ((readString = buf.readLine()) != null) {
				tv.append(readString);
				tv.append("\r\n");
			}

		} catch (FileNotFoundException e) {
			tv.append(" \n File not Found! ReadFile() Broken!");
			e.printStackTrace();

		} catch (IOException e) {
			tv.append(" \n IOException! ReadFile() Broken!");
			e.printStackTrace();

		}
	}
	
	public void DeleteFile(String fileName)
	//////////////////////////////////////////////////////////////////////////////////////////
	//NAME: DeleteFile(String fileName) 													//
	//AUTHOR: CDT Peter Lofreddo 															//
	//LAST MODIFIED: 09 February 2012 														//
	//DESCRIPTION: Deletes a file in the Nullwall Directory									//
	//LIMITATIONS: Must be in Nullwall Directory											//
	//																						//
	//////////////////////////////////////////////////////////////////////////////////////////
{
	File root = new File(Environment.getExternalStorageDirectory(),"Nullwall");
	File file = new File(root, fileName);
	if (!file.delete())
	{
		Toast.makeText(this, "File Not deleted! "+ fileName + " not found",
				Toast.LENGTH_SHORT).show();	
	}
}

	public void ClearFile(String fileName) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ClearLog() 																	//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 9 February 2012 														//
		// DESCRIPTION: Clears a file located in Nullwall Directory. Does not Delete File.		//
		// CITATIONS: N/A																		//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File root = new File(Environment.getExternalStorageDirectory(),
					"Nullwall");
			if (!root.exists()) {
				root.mkdirs();
			}
			File gpxfile = new File(root, fileName);
			FileWriter writer = new FileWriter(gpxfile, false);
			writer.write("");
			writer.flush();
			writer.close();
		} catch (FileNotFoundException e) {
			tv.append(" \n File not Found! ClearLog() Broken!");
			e.printStackTrace();

		} catch (IOException e) {
			tv.append(" \n IOException! ClearLog() Broken!");
			e.printStackTrace();
		}
	}
	
	public void AppendFile(String sBody, String fileName) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: AppendLogFile(sBody) 															//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 09 February 2012 														//
		// DESCRIPTION: Adds text to a file located in the Nullwall Directory					//
		// does not need CreateLogFile() to first append to file; Used for clarity				//
		// CITATIONS: Adapted from http://stackoverflow.com/questions/4580683/					//
		// android-java-writing-text-file-to-sd-card 											//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File root = new File(Environment.getExternalStorageDirectory(),
					"Nullwall");
			if (!root.exists()) {
				root.mkdirs();
			}
			tv.append("\nLog File Created In Directory: " + root);
			File gpxfile = new File(root, fileName);
			FileWriter writer = new FileWriter(gpxfile, true);
			writer.write(sBody.toLowerCase() + "\n");
			writer.flush();
			writer.close();
			Toast.makeText(this, "Log Successfully Created!",
					Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			tv.append(" \n File not Saved! CreateFile() Broken!");
		}
	}

	public void CreateFile(String fileName)
	//////////////////////////////////////////////////////////////////////////////////////////
	// NAME: CreateLogFile() 																//
	// AUTHOR: CDT Peter Lofreddo 															//
	// LAST MODIFIED: 09 February 2012 														//
	// DESCRIPTION: Creates a blank file in the Nullwall directory.							//
	// 																						//
	// AppendLogFile(String sBody). It has been added to provide clarity an					//
	// intuitive codebase 																	//
	// does not need CreateLogFile() to first append to file; Used for clarity				//
	// 																						//
	// CITATIONS: Adapted from http://stackoverflow.com/questions/4580683/ 					//
	// android-java-writing-text-file-to-sd-card 											//
	// 																						//
	//////////////////////////////////////////////////////////////////////////////////////////
{
	try {
		File root = new File(Environment.getExternalStorageDirectory(),
				"Nullwall");
		if (!root.exists()) {
			root.mkdirs();
		}
		tv.append("\nLog File Created In Directory: " + root);
		File gpxfile = new File(root, fileName);
		FileWriter writer = new FileWriter(gpxfile, true);
		writer.write("");
		writer.flush();
		writer.close();
		Toast.makeText(this, fileName + " Log Successfully Created!",
				Toast.LENGTH_SHORT).show();
	} catch (IOException e) {
		tv.append(" \n File not Saved! CreateLogFile() Broken!");
	}
}
	
	public void RemoveStrFromFile(String blackorwhite, String packageName)
	//////////////////////////////////////////////////////////////////////////////////////////
	//NAME: DoWork(String deleteFromFile) 													//
	//AUTHOR: CDT Peter Lofreddo 															//
	//LAST MODIFIED: 09 February 2012 														//
	//DESCRIPTION: Deletes a String from a file												//
	//LIMITATIONS: Search Queries cast to lowercase for ease of use.						//
	//CITATIONS: Adapted from http://stackoverflow.com/questions/1377279/					//
	//java-find-a-line-in-a-file-and-remove													//
	//																						//
	//////////////////////////////////////////////////////////////////////////////////////////
//assumes black_list.txt or white_list.txt is 
//already created in mnt/sdcard/Nullwall directory
{

try{
//Makes sure programmer uses black or white as argument for method.
if (!blackorwhite.equalsIgnoreCase("black"))
{
if (!blackorwhite.equalsIgnoreCase("white"))
{
Toast.makeText(this, "ERROR:RemoveFromList() must have white or black as an argument",
Toast.LENGTH_SHORT).show();
}
}

//locates a black_list.txt or white_list.txt in Nullwall Directory
File root = new File(Environment.getExternalStorageDirectory(),"Nullwall");
File file = new File(root, blackorwhite +  "_list.txt");
File temp = new File(root,"temp.txt");

//creates buffers
BufferedReader bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
PrintWriter printerWriter = new PrintWriter(new FileWriter(temp.getAbsolutePath()));


String line = null; 
//Read from the original file and write to the new 
//unless content matches data to be removed. 
while ((line = bufferedReader.readLine()) != null) { 
if (!line.trim().equalsIgnoreCase(packageName)) { 
printerWriter.println(line + "\r\n"); 
printerWriter.flush(); 
} 
} 
printerWriter.close(); 
bufferedReader.close(); 

//Delete the original file 
if (!file.delete()) { 
System.out.println("Could not delete file, error RemoveFromList()");
return; 
} 

//Rename the new file to the filename the original file had. 
if (!temp.renameTo(file)) 
System.out.println("Could not rename file, error RemoveFromList()"); 

} 
catch (FileNotFoundException ex) { 
ex.printStackTrace(); 
} 
catch (IOException ex) { 
ex.printStackTrace(); 
} 

}
	
	public boolean SearchFile(String searchString,String fileName, Boolean caseSensitive) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: SearchFile(String searchString,String fileName, Boolean caseSensitive)			//
		// AUTHOR: CDT Peter Lofreddo															//
		// LAST MODIFIED: 09 February 2012 														//
		// DESCRIPTION: Searches in file for string in Nullwall Directory. 						//
		// caseSensitive = true for Case sensitive 												//
		// searching, choose false to ignore case 												//
		// CITATIONS: Adapted																	//
		// From http://stackoverflow.com/questions/5912753/java-find-and-replace-text			//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		boolean unfound = true;
		try {
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/Nullwall/" + fileName);
			FileInputStream fileIS = new FileInputStream(f);
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					fileIS));
			String line;
			while ((line = buf.readLine()) != null) {
				line = buf.readLine();
				if (caseSensitive) {
					if (line.equals(searchString)) {
						unfound = false;
						tv.append("You found it! case sensitive");
					}
				} else if (line.equalsIgnoreCase(searchString)) {
					unfound = false;
					tv.append("You found it! not case sensitive");
				}
			}
			if (unfound) {
				tv.append("You did not find " + searchString
						+ " in the log file \n");
			}
			return unfound;
		} catch (FileNotFoundException e) {
			tv.append(" \n File not Found! SearchFile() Broken!");
			e.printStackTrace();
			return true;

		} catch (IOException e) {
			tv.append(" \n IOException! SearchFile() Broken!");
			e.printStackTrace();
			return true;
		}
	}
}

